// 引入接口文件
import { queryAllAddress, getCityEstateList, addCoupon, editCoupon, getCouponDetail } from './couponAddServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge, get, pick } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import { makeAddress } from "utils/util"
import AppBus from 'utils/bus'

// 初始默认状态
const defultState = {
  loading: false,
  btnLoading: false,
	detail: {
		couponsConfigId: '',//优惠券id
		type: '',//优惠券类型
		name: '',//优惠券名称
		circulation: '',//发行量
		accountLimit: 1,//每个账号领取限制
		accountDayLimit: 1,//每个账号每天领取限制
		onlineTime: '',//上架时间
		offlineTime: '',//下架时间
		startTime: '',//有效期开始日期
		expireDate: '',//过期日期
		remark: '',//备注
		bgImgs: '',//优惠券背景图
		amount: '',//额度或金额
		province: '',//省
		city: '',//市
		productIds: [],//楼盘id
		
	},
	currentStep: 0,//当前进度
	areaList: [],//省市区列表
	estateList: [],//市对应的楼盘项目
	//全选按钮
	indeterminate: false,
	checkAll: false,
	selectItem:[],
}

// 声明module
const tmpModule = {
	namespace: 'couponAddModel',
	// 默认状态
	state: cloneDeep(defultState),
	// 入口函数(先执行)
	subscriptions: {
		setup({ dispatch, history }) {
			history.listen((location) => {
				let { pathname, query } = location;
				// 页面路由匹配时执行
				if ('' + tmpModule.pathname === '' + pathname) {
					
					//debugger
					dispatch({ type: 'updateStore', payload: cloneDeep(defultState) })
					if (!!get(query, 'couponsConfigId', '')) {
						dispatch({ type: 'getDetail', payload: { params: { id: query.couponsConfigId } } })
						dispatch({ type: 'app/setTabTitle', payload: { title: '编辑优惠券', location } });
					} else {
						dispatch({ type: 'app/setTabTitle', payload: { title: '新增优惠券', location } });
					}
					dispatch({ type: 'getAreaList', payload: {} });
          dispatch({ type: 'getCityEstateList', payload: { params: { province:'', city: '' } } })
				}
			})
		},
	},

	// 方法列表
	effects: {
		// 查询记录
		*getDetail({ payload }, { put, call, select }) {
			try {
				let {detail} = yield select(state => state[tmpModule.namespace])
				const { data, success, msg } = yield call(getCouponDetail, parse(payload.params))
				if (success) {
					// let productIds = []
					// data.couponsConfigProductResDtos && data.couponsConfigProductResDtos.forEach((e, i) => { productIds.push(e.productId) })
					// data.productIds = productIds;
					//设置所属城市,获取城市的所有楼盘
					console.log(data,'data')
					let selectItem =[]
					selectItem = data.couponsConfigProductResDtos
					console.log(selectItem)
					if (data.products) {
						for (let i = 0; i < data.products.length; i++) {
							detail.productIds.push(data.couponsConfigProductResDtos[i].productId)
						}
					}//todo 上面的作用是啥？---
					if (data.couponsConfigProductResDtos) {
						for (let i = 0; i < data.couponsConfigProductResDtos.length; i++) {
							detail.productIds.push(data.couponsConfigProductResDtos[i].productId)
						}
					}
					  //console.log(detail,'detail')
					if (get(data, 'couponsConfigProductResDtos[0].province', '') && get(data, 'couponsConfigProductResDtos[0].city', '')) {
						data.province = data.couponsConfigProductResDtos[0].province;
						data.city = data.couponsConfigProductResDtos[0].city;
						yield put({ type: 'getCityEstateList', payload: { params: { province: data.province, city: data.city } } })
					}
					
					yield put({ type: 'updateStore', payload: { detail: Object.assign({}, detail, data),selectItem } })
					console.log(moment(detail.onlineTime).isAfter(moment()))
					//debugger

				}
			} catch (e) {
				console.error(e)
			}
		},

		*getAreaList({ payload }, { put, call, select }) {
			try {
				const data = yield call(queryAllAddress, {})
				if (data.success) {
					
					let areaList = []
					//澳门与北京只有两级
					let arr = [data.data[0]]
					let attr = [data.data[data.data.length - 1]]
					data.data[0] = {
						label: "北京",
						value: "110100",
						children: arr
					}
					data.data[data.data.length - 1] = {
						label: "澳门",
						value: "820000",
						children: attr
					}
					//去掉第三级，
					areaList = makeAddress(data.data, 2)
					console.log(areaList)
					yield put({ type: 'updateStore', payload: { areaList } });
				}
			} catch (e) {
			}
		},

		*getCityEstateList({ payload }, { put, call, select }) {
			try {
				const data = yield call(getCityEstateList, { pageNo: 1, pageSize: 1000, ...payload.params })
				if (data.success) {
					let estateList = data.rows
					estateList && estateList.forEach((e, i) => { e.label = e.name; e.value = e.productId })
					yield put({ type: 'updateStore', payload: { estateList } });
				}
			} catch (e) {
			}
		},

		*submitCoupon({ payload }, { put, call, select }) {
			try {
			let state = yield select(state => state[tmpModule.namespace])
			let  {detail} = state
			let params = cloneDeep(state.detail)
			let method = addCoupon;
			if (!params.couponsConfigId) {
				//新增
				// delete params.couponsConfigId
				params=pick(params,['name','bgImgs','type','scene','amount','startTime','expireDate','circulation','accountLimit','accountDayLimit','remark','onlineTime','offlineTime','productIds'])
				method = addCoupon;
			} else {
				//编辑
				params=pick(params,['couponsConfigId','name','bgImgs','type','scene','amount','startTime','expireDate','circulation','accountLimit','accountDayLimit','remark','onlineTime','offlineTime','productIds'])
				method = editCoupon
			}
			
				let data = yield call(method, params)
				if (data.success) {
					// var now = moment();
					//console.log()
					if(moment(detail.onlineTime).isAfter(moment().add(10, 'minutes'))){
						message.success(`您设置的优惠券将在${detail.onlineTime}后10分钟内生效，请关注`);
					}else{
						message.success(`您设置的优惠券将在10分钟之内生效，请稍候`);
					}
					hashHistory.push('/home/infoAdmin/couponList')
				
				}
			} catch (e) {
			}
		},

	},

	// 存入状态机
	reducers: {
		updateStore(preState, action) {
			return Object.assign({}, preState, action.payload)
		},
	}
}

export default tmpModule
